package com.bizdk.generator.service.impl;

import cn.hutool.core.text.NamingCase;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bizdk.generator.entity.gen.TableColumn;
import com.bizdk.generator.entity.gen.TypeMapping;
import com.bizdk.generator.mapper.TableColumnMapper;
import com.bizdk.generator.service.TableColumnService;
import com.bizdk.generator.service.TypeMappingService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 表字段
 */
@Service
@AllArgsConstructor
public class TableColumnServiceImpl extends ServiceImpl<TableColumnMapper, TableColumn>
        implements TableColumnService {
    
    private final TypeMappingService fieldTypeService;
    
    @Override
    public List<TableColumn> getByTableId(Long tableId) {
        return baseMapper.getByTableId(tableId);
    }
    
    @Override
    public void deleteBatchTableIds(Long[] tableIds) {
        baseMapper.deleteBatchTableIds(tableIds);
    }
    
    @Override
    public void updateTableColumn(Long tableId, List<TableColumn> columns) {
        // 更新字段数据
        int sort = 0;
        for (TableColumn tableField : columns) {
            tableField.setSort(sort++);
            this.updateById(tableField);
        }
    }
    
    @Override
    public void initColumnList(List<TableColumn> tableColumnList) {
        // 字段类型、属性类型映射
        Map<String, TypeMapping> fieldTypeMap = fieldTypeService.getMap();
        int index = 0;
        for (TableColumn column : tableColumnList) {
            column.setAttrName(NamingCase.toCamelCase(column.getColumnName()));
            // 获取字段对应的类型
            TypeMapping fieldTypeMapping = fieldTypeMap.get(column.getColumnType().toLowerCase());
            if (fieldTypeMapping == null) {
                // 没找到对应的类型，则为Object类型
                column.setAttrType(Object.class.getSimpleName());
            } else {
                column.setAttrType(fieldTypeMapping.getAttrType());
                column.setPackageName(fieldTypeMapping.getPackageName());
            }
            column.setAttrLabel(column.getColumnComment());
            
            column.setAddItem(true);
            if (column.isPkItem()) {
                column.setEditItem(false);
            } else {
                column.setEditItem(true);
            }
            column.setGridItem(true);
            column.setQueryItem(true);
            column.setQueryType("EQ");
            column.setReqItem(false);
            column.setHtmlType("input");
            column.setDictType("");
            column.setSort(index++);
        }
    }
}